package com.remotephone.myapplication

import android.accessibilityservice.AccessibilityService
import android.accessibilityservice.AccessibilityServiceInfo
import android.app.*
import android.content.Context
import android.content.Intent
import android.graphics.Bitmap
import android.os.*
import android.util.Log
import android.view.accessibility.AccessibilityEvent
import androidx.core.app.NotificationCompat
import androidx.core.content.ContextCompat
import java.io.File
import java.io.FileOutputStream
import java.util.concurrent.Executor

class AccessibilityScreenshotService : AccessibilityService() {
    
    companion object {
        private const val TAG = "AccessibilityScreenshot"
        private const val CHANNEL_ID = "accessibility_screenshot_channel"
        private const val NOTIFICATION_ID = 2002
        
        private var serviceInstance: AccessibilityScreenshotService? = null
        private var callback: ScreenshotCallback? = null
        
        interface ScreenshotCallback {
            fun onSuccess(bitmap: Bitmap)
            fun onError(message: String)
        }
        
        fun takeScreenshot(callback: ScreenshotCallback) {
            this.callback = callback
            if (serviceInstance != null) {
                serviceInstance?.performScreenshot()
            } else {
                callback.onError("无障碍服务未连接")
            }
        }
        
        fun isServiceConnected(): Boolean {
            return serviceInstance != null
        }
    }
    
    override fun onCreate() {
        super.onCreate()
        serviceInstance = this
        createNotificationChannel()
        startForeground(NOTIFICATION_ID, createNotification())
        Log.d(TAG, "AccessibilityScreenshotService created")
    }
    
    override fun onServiceConnected() {
        super.onServiceConnected()
        Log.d(TAG, "AccessibilityScreenshotService connected")
        
        // 配置服务参数
        val info = AccessibilityServiceInfo().apply {
            eventTypes = AccessibilityEvent.TYPE_NOTIFICATION_STATE_CHANGED
            feedbackType = AccessibilityServiceInfo.FEEDBACK_GENERIC
            flags = AccessibilityServiceInfo.FLAG_INCLUDE_NOT_IMPORTANT_VIEWS
        }
        serviceInfo = info
    }
    
    override fun onAccessibilityEvent(event: AccessibilityEvent?) {
        // 无障碍事件处理（这里不需要特殊处理）
    }
    
    override fun onInterrupt() {
        Log.d(TAG, "AccessibilityScreenshotService interrupted")
    }
    
    private fun performScreenshot() {
        Log.d(TAG, "开始无障碍截图，Android版本: API ${Build.VERSION.SDK_INT}")
        
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
            // Android 11+ 直接使用API
            takeScreenshotDirect()
        } else {
            Log.w(TAG, "Android版本过低，需要API 30+")
            saveErrorExplanation(-20, "Android版本过低 (API ${Build.VERSION.SDK_INT})")
            callback?.onError("需要Android 11+ (当前: API ${Build.VERSION.SDK_INT})")
        }
    }
    
    private fun takeScreenshotDirect() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
            try {
                Log.d(TAG, "使用无障碍服务直接截图")
                
                val executor: Executor = ContextCompat.getMainExecutor(this)
                val screenshotCallback = object : TakeScreenshotCallback {
                    override fun onSuccess(screenshot: ScreenshotResult) {
                        Log.d(TAG, "无障碍截图成功！")
                        
                        try {
                            // 获取硬件缓冲区
                            val hardwareBuffer = screenshot.hardwareBuffer
                            val colorSpace = screenshot.colorSpace
                            
                            // 创建Bitmap
                            val bitmap = Bitmap.wrapHardwareBuffer(hardwareBuffer, colorSpace)
                            
                            if (bitmap != null) {
                                Log.d(TAG, "Bitmap创建成功，尺寸: ${bitmap.width}x${bitmap.height}")
                                
                                // 保存到文件
                                saveScreenshot(bitmap)
                                
                                // 调用回调
                                callback?.onSuccess(bitmap)
                            } else {
                                Log.e(TAG, "Bitmap创建失败")
                                callback?.onError("Bitmap创建失败")
                            }
                            
                            // 释放资源
                            hardwareBuffer.close()
                        } catch (e: Exception) {
                            Log.e(TAG, "处理截图结果失败", e)
                            saveErrorExplanation(-2, "处理截图失败: ${e.message}")
                            callback?.onError("处理截图失败: ${e.message}")
                        }
                    }
                    
                    override fun onFailure(errorCode: Int) {
                        Log.e(TAG, "无障碍截图失败，错误代码: $errorCode")
                        val errorMessage = when (errorCode) {
                            1 -> "内部错误"
                            2 -> "截图间隔太短" 
                            3 -> "无效显示"
                            4 -> "无效窗口"
                            5 -> "不支持的显示布局"
                            else -> "未知错误 ($errorCode)"
                        }
                        
                        Log.e(TAG, "错误详情: $errorMessage")
                        
                        // 保存错误说明
                        saveErrorExplanation(errorCode, errorMessage)
                        
                        callback?.onError("$errorMessage (代码: $errorCode)")
                    }
                }
                
                // 直接调用API
                takeScreenshot(android.view.Display.DEFAULT_DISPLAY, executor, screenshotCallback)
                
            } catch (e: Exception) {
                Log.e(TAG, "调用无障碍截图API失败", e)
                saveErrorExplanation(-3, "API调用异常: ${e.message}")
                callback?.onError("API调用失败: ${e.message}")
            }
        }
    }
    
    private fun saveScreenshot(bitmap: Bitmap): String? {
        return try {
            val screenshotsDir = File(cacheDir, "screenshots")
            if (!screenshotsDir.exists()) {
                screenshotsDir.mkdirs()
            }
            
            val timestamp = System.currentTimeMillis()
            val screenshotFile = File(screenshotsDir, "accessibility_screenshot_$timestamp.png")
            
            FileOutputStream(screenshotFile).use { out ->
                bitmap.compress(Bitmap.CompressFormat.PNG, 100, out)
            }
            
            Log.d(TAG, "无障碍截图已保存: ${screenshotFile.absolutePath}")
            screenshotFile.absolutePath
            
        } catch (e: Exception) {
            Log.e(TAG, "保存截图失败", e)
            null
        }
    }
    
    private fun createNotificationChannel() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            val channel = NotificationChannel(
                CHANNEL_ID,
                "无障碍截图服务",
                NotificationManager.IMPORTANCE_LOW
            ).apply {
                description = "提供无障碍截图功能"
            }
            val notificationManager = getSystemService(NotificationManager::class.java)
            notificationManager.createNotificationChannel(channel)
        }
    }
    
    private fun createNotification(): Notification {
        return NotificationCompat.Builder(this, CHANNEL_ID)
            .setContentTitle("无障碍截图服务")
            .setContentText("Android 11+无障碍截图已启用")
            .setSmallIcon(android.R.drawable.ic_menu_camera)
            .setOngoing(true)
            .build()
    }
    
    private fun saveErrorExplanation(errorCode: Int, errorMessage: String) {
        try {
            val explanationDir = File(cacheDir, "screenshots")
            if (!explanationDir.exists()) {
                explanationDir.mkdirs()
            }
            
            val explanationFile = File(explanationDir, "accessibility_error_explanation.txt")
            explanationFile.writeText("""
                无障碍截图错误分析
                ================
                
                错误代码: $errorCode
                错误描述: $errorMessage
                
                无障碍截图失败的可能原因：
                1. Android版本不支持 (需要Android 11+)
                2. 无障碍服务配置不完整
                3. 系统安全策略限制
                4. 当前窗口状态不允许截图
                
                解决建议：
                1. 确认Android版本 >= 11 (API 30)
                2. 在设置->无障碍中重新启用服务
                3. 确保应用有足够的无障碍权限
                4. 尝试在不同的应用界面进行截图
                
                技术细节：
                - 无障碍截图API: AccessibilityService.takeScreenshot()
                - 配置文件: accessibility_service_config.xml
                - 权限要求: canTakeScreenshot="true"
                - 实现方式: 直接API调用 (API 30+)
                
                测试时间: ${System.currentTimeMillis()}
                设备API级别: ${Build.VERSION.SDK_INT}
                
                ${if (errorCode == 5 || errorCode == -3) {
                    """
                    特别说明 (错误代码 $errorCode):
                    - 这个错误通常表示当前显示布局不支持截图
                    - 可能是因为有悬浮窗或特殊窗口层级
                    - 无障碍服务截图可能无法完全绕过应用层浮窗
                    - 建议尝试其他截图方案
                    """.trimIndent()
                } else { "" }}
            """.trimIndent())
            
            Log.d(TAG, "无障碍错误说明已保存: ${explanationFile.absolutePath}")
            
        } catch (e: Exception) {
            Log.e(TAG, "创建错误说明文件失败", e)
        }
    }
    
    override fun onDestroy() {
        serviceInstance = null
        super.onDestroy()
        Log.d(TAG, "AccessibilityScreenshotService destroyed")
    }
} 